package com.mmall.service;

import com.google.common.collect.Lists;
import com.mmall.common.RequestHolder;
import com.mmall.dao.SysRoleAclMapper;
import com.mmall.model.SysRoleAcl;
import com.mmall.util.IpUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class SysRoleAclService {

    @Resource
    private SysRoleAclMapper mapper;
    @Resource
    private SysLogService sysLogService;

    public void changeRoleAcls(int roleId, List<Integer> aclIdList) {
        //取出之前分配过的id
        List<Integer> originAclIdList = mapper.getAclIdListByRoleIdList(Lists.<Integer>newArrayList(roleId));
        //判断之前的和更新的权限id是否相同
        if (originAclIdList.size() == aclIdList.size()) {
            Set<Integer> aclIdSet = new HashSet<>(aclIdList);
            Set<Integer> originAclIdSet = new HashSet<>(originAclIdList);
            //根据内容移除，如果什么都不剩，那么就说明相等
            originAclIdSet.removeAll(aclIdList);
            if (CollectionUtils.isEmpty(originAclIdSet)) {
                return;
            }
        }
        updateRoleAcls(roleId, aclIdList);

        sysLogService.saveAclRoleLog(roleId,originAclIdList,aclIdList);
    }

    @Transactional
    public void updateRoleAcls(int roleId, List<Integer> aclIdList) {
       mapper.deleteByRoleId(roleId);
       if (CollectionUtils.isEmpty(aclIdList)){
           return;
       }
       List<SysRoleAcl> roleAcls = Lists.newArrayList();
       for (Integer aclId : aclIdList){
           SysRoleAcl sysRoleAcl = SysRoleAcl.builder().roleId(roleId).aclId(aclId)
                   .operateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()))
                   .operateTime(new Date())
                   .operator(RequestHolder.getCurrentUser().getUsername())
                   .build();
           roleAcls.add(sysRoleAcl);
       }
       mapper.batchInsert(roleAcls);
    }
}
